﻿using System;
using System.Transactions;
using System.Web;
using CrazyTalk.BLL;
using CrazyTalk.Caching;
using CrazyTalk.Common;
using CrazyTalk.Models;
using CrazyTalk.Models.EnumList;
using CrazyTalk.Web.UI;
using Newtonsoft.Json;
namespace CrazyTalk.Web.Actions
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    public class Login : HttpHandlerBase
    {
        string _userId;
        string _pwd;
        //string vcode;
        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            _userId = Query("LoginName").Trim();
            _pwd = Query("LoginPwd").Trim();
            //vcode = Query("txtVcode").Trim();
            //_state = Query("txtState").Trim();
            string result = LoginHandler();
            ChangCode(result);
            context.Response.Write(result);
        }
        public string LoginHandler()
        {
            if (string.IsNullOrEmpty(_userId) || string.IsNullOrEmpty(_pwd)
                //|| string.IsNullOrEmpty(vcode)
                )
            {
                return "0";
            }
            //图片验证码处理
            //XHCache cache = XHCache.GetCacheService();
            //string codecacheKey = "/login/_" + "vcode" + vcode.ToLower();
            //string code = cache.RetrieveObject(codecacheKey) == null ? "" : cache.RetrieveObject(codecacheKey).ToString();
            //if (vcode.ToLower() != code)
            //{
            //    return JsonConvert.SerializeObject(2);
            //}
            UserInfo userInfo = UserInfoBLL.Instance.GetModel(_userId);
            if (userInfo == null)
            {
                return JSON.GetJsonMessage(false, "账号不存在");
            }
            UserStatusType status = (UserStatusType)userInfo.UserStatus;
            if ((status & UserStatusType.禁用) == UserStatusType.禁用)
            {
                return JSON.GetJsonMessage(false, "此账号已被禁用");
            }
            string md5Pwd = PasswordHelper.GetPasswordHash(_pwd, userInfo.PswSalt, userInfo.PswFormat);
            //加入导入数据密码为sha1判断逻辑
            if (userInfo.PswSalt == "sha1")
            {
                if (userInfo.PswHash.Equals((PasswordHelper.GetPasswordSha1(_pwd)), StringComparison.OrdinalIgnoreCase) == false)
                {
                    return JSON.GetJsonMessage(false, "密码错误");
                }
                userInfo.PswSalt = "-1";
                userInfo.PswHash = md5Pwd;
                UserInfoBLL.Instance.Update(userInfo);
            }
            else
            {
                if (userInfo.PswHash != md5Pwd)
                {
                    return JSON.GetJsonMessage(false, "密码错误");
                }
            }
            UserLoginSign(userInfo);
            return JSON.GetJsonMessage(true, new
            {
                userInfo.UserId,
                RealName = userInfo.RealityName,
                userInfo.LastLoginIp,
                LoginTime = userInfo.LastLoginTime.ToFormater(Formater.DateTime_yyyyMMddHHmmss),
                userInfo.RoleId,
                RoleName = ((RoleType)userInfo.RoleId).ToString()
            });
            //return JsonConvert.SerializeObject(model);
        }
        public new bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 用户登陆状态进行签名处理
        /// 记录cookie状态，录入数据库，添加进缓存
        /// </summary>
        /// <param name="model"></param>
        public static void UserLoginSign(UserInfo model)
        {
            UserSession session = new UserSession();
            session.UserToken = SequenceNo.CreateByGen('T').ToString();
            session.UserID = model.UserId;
            session.RowID = model.RoleId;
            session.NickName = model.NickName;
            session.IP = RequestHelper.GetIP();
            session.LastActiveTime = DateTime.Now;
            session.StampTime = DateTime.Now;
            session.ActionType = "S";
            session.Resource = "M";
            //更新登录IP地址
            model.LoginIp = model.LastLoginIp;
            model.LastLoginIp = RequestHelper.GetIP();
            model.LoginTime = model.LastLoginTime;
            model.LastLoginTime = DateTime.Now;
            using (TransactionScope scop = new TransactionScope())
            {
                //记录进数据库
                UserSessionBLL bll = UserSessionBLL.Instance;
                bll.Add(session);
                UserInfoBLL.Instance.AddCache(model);
                //更新登录IP地址
                UserInfoBLL.Instance.Update(model);
                Facade.SetLogin(model.UserId);
                scop.Complete();
            }
        }
        public void ChangCode(string result)
        {
            if (result == "0")
            {
                JsonConvert.SerializeObject(result);
            }
            else
            {
                DefaultCache cache = DefaultCache.GetCacheService();
                string cacheKey = "/login/_" + _userId;
                int? count = Convert.ToInt32(cache.RetrieveObject(cacheKey));
                if (count >= 0)
                {
                    cache.RemoveObject(cacheKey);
                }
            }
        }
    }
    public class Data
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserId { get; set; }
        /// <summary>
        /// 登录IP
        /// </summary>
        public string LoginIP { get; set; }
        /// <summary>
        /// 登录时间
        /// </summary>
        public string LoginTime { get; set; }
        /// <summary>
        /// 角色类型
        /// </summary>
        public int RoId { get; set; }
    }
}